package com.cupdata.marathon.common;

import com.cupdata.marathon.bean.Result;
import com.cupdata.marathon.bean.User;
import com.cupdata.marathon.definition.CouponTp;
import com.cupdata.marathon.definition.DownRslt;
import com.cupdata.marathon.definition.MemTp;
import com.cupdata.marathon.param.download.DownloadRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class AuthCheckService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private static final int PLAIN_USER_COUPON_SUM_COUNT = 2;
    private static final int PLAIN_USER_COUPON_WORTH_SUM = 5000;

    private static final int MEMBER_USER_COUPON_ONE_COUNT = 2;
    private static final int MEMBER_USER_COUPON_TWO_COUNT = 2;
    private static final int MEMBER_USER_COUPON_WORTH_SUM = 10000;


    public Result districtCheck(DownloadRequest downloadRequest){
        if(!"310000".equals(downloadRequest.getCityCd())){
            logger.info("该用户{}领取失败，{}",downloadRequest.getUserId(), DownRslt.R000030.getMsg());
            return new Result(DownRslt.R000030.getMsg(),DownRslt.R000030.getCode());
        }
        return new Result();
    }

    public Result userStatusCheck(String userId, String couponTp, String membership, User user){
        if (MemTp.MEMBER.getCode().equals(membership)) {
            // 用户为会员
            if (couponTp.startsWith("1")) {
                if (user.getOneCount() >= MEMBER_USER_COUPON_ONE_COUNT) {
                    logger.warn("该会员用户{}领取失败，{}", userId, DownRslt.R000020.getMsg());
                    return new Result(DownRslt.R000020.getMsg(), DownRslt.R000020.getCode());
                }
            } else {
                if (user.getTwoCount() >= MEMBER_USER_COUPON_TWO_COUNT) {
                    logger.warn("该会员用户{}领取失败，{}", userId, DownRslt.R000020.getMsg());
                    return new Result(DownRslt.R000020.getMsg(), DownRslt.R000020.getCode());
                }
            }

            if (user.getCouponWorth() + CouponTp.getValue(couponTp) > MEMBER_USER_COUPON_WORTH_SUM) {
                logger.warn("该会员用户{}领取失败，{}", userId, DownRslt.R000010.getMsg());
                return new Result(DownRslt.R000010.getMsg(), DownRslt.R000010.getCode());
            }
        } else {
            // 用户为非会员
            if (user.getOneCount() + user.getTwoCount() >= PLAIN_USER_COUPON_SUM_COUNT) {
                logger.warn("该用户{}领取失败，{}", userId, DownRslt.R000020.getMsg());
                return new Result(DownRslt.R000020.getMsg(), DownRslt.R000020.getCode());
            }
            if (user.getCouponWorth() + CouponTp.getValue(couponTp) > PLAIN_USER_COUPON_WORTH_SUM) {
                logger.warn("该用户{}领取失败，{}", userId, DownRslt.R000010.getMsg());
                return new Result(DownRslt.R000010.getMsg(), DownRslt.R000010.getCode());
            }
        }
        return null;
    }

}
